package com.c611.smartclassroom.controller;

import com.c611.smartclassroom.component.LogHandlerInterceptor;
import com.c611.smartclassroom.mapper.*;
import com.c611.smartclassroom.mapper.Ext.GateWayMapperExt;
import com.c611.smartclassroom.model.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 本类是关于手机端的api
 */
@RestController
@RequestMapping("/phone")
public class PhoneController {

    @Autowired
    UserMapper userMapper;

    @Autowired
    LogMapper logMapper;

    @Autowired
    ScheduleMapper scheduleMapper;

    @Autowired
    GateWayMapper gateWayMapper;

    @Autowired
    DeviceMapper deviceMapper;

    @Autowired
    BuildMapper buildMapper;

    @Autowired
    ClassRoomMapper classRoomMapper;

    @Autowired
    GateWayMapperExt gateWayMapperExt;

    @Autowired
    WorkOrderMapper workOrderMapper;

//    ==============================================================
//    第一次给手机端的接口
    /**
     * 返回当前用户所在学校的全部楼
     * @return
     */
    @PostMapping("/getAllBuildByUser")
    public List<Build> getAllBuildByUser(HttpSession session) {
        //1、取出登陆用户的学校id
        User user = (User) session.getAttribute("loginPhoUser");
        if(user == null) return null;
        String schoolid = user.getSchoolid();
//        String schoolid = "001";
        //2、去查询该学校id下的所有教学楼
        BuildExample buildExample = new BuildExample();
        buildExample.createCriteria()
                .andSchoolidEqualTo(schoolid)
                .andDelflagEqualTo(0);
        return  buildMapper.selectByExample(buildExample);
    }

    /**
     * 根据教学楼id来增加教室
     */
    @PostMapping("/addClassRoom")
    public int addClassRoom(@RequestBody AddGateWaysDto addGateWaysDto) {
        String buildId = addGateWaysDto.getBuildId();
        String classroom = addGateWaysDto.getClassroom();
        List<String> gateways = addGateWaysDto.getGateways();
        if(buildId == null || classroom == null) return 0;
        //添加教室
        ClassRoom classRoom = new ClassRoom();
        classRoom.setTbuildid(buildId);
        classRoom.setClassroomid(buildId + classroom);
        classRoom.setClassroom(classroom);
        classRoom.setAddtime(new Date());
        classRoomMapper.insertSelective(classRoom);
        //遍历集合，添加网关
        long gataWayCount = gateWayMapper.countByExample(null);
        for (String gateway : gateways) {
            //进行插入
            GateWay newgateWay = new GateWay();
            newgateWay.setGatewayid(++gataWayCount + "");
            newgateWay.setGatewaymac(gateway);
            newgateWay.setClassroomid(buildId + classroom);
            newgateWay.setActime(new Date());
            gateWayMapperExt.insertMySelective(newgateWay,buildId);
        }

        return 1;
    }

    /**
     * ###查询当前登陆用户所在学校的所有教学楼
     */
    @PostMapping("/queryAllBuid")
    public List<BuildAndClassDto> queryAllBuidAndClass(HttpSession session) {
        //1、取出登陆用户的用户信息
        User user = (User) session.getAttribute("loginPhoUser");
        if(user == null) return null;
        String schoolid = user.getSchoolid();
//        String schoolid = "001";
        //根据学校id去查询所有的教学楼
        BuildExample buildExample = new BuildExample();
        buildExample.createCriteria()
                .andSchoolidEqualTo(schoolid).andDelflagEqualTo(0);
        List<Build> builds = buildMapper.selectByExample(buildExample);
        List<BuildAndClassDto> buildAndClassDtos = new ArrayList<>();
        //遍历所有楼，去封装放回对象
        for (Build build : builds) {
            ClassRoomExample classRoomExample = new ClassRoomExample();
            classRoomExample.createCriteria()
                    .andTbuildidEqualTo(build.getTbuildid())
                    .andDelflagEqualTo(0);
            List<ClassRoom> classrooms = classRoomMapper.selectByExample(classRoomExample);
            List<BuildAndClassDto.ClassroomBean> classroomBeans = new ArrayList<>();
            for (ClassRoom classRoom : classrooms) {
                BuildAndClassDto.ClassroomBean classroomBean = new BuildAndClassDto.ClassroomBean();
                classroomBean.setClassroomid(classRoom.getClassroomid());
                classroomBean.setClassroomname(classRoom.getClassroom());
                classroomBean.setAddtime(classRoom.getAddtime());
                classroomBeans.add(classroomBean);
            }
            BuildAndClassDto buildAndClassDto = new BuildAndClassDto();
            buildAndClassDto.setTbuildid(build.getTbuildid());
            buildAndClassDto.setTbuildname(build.getTbuildname());
            buildAndClassDto.setAddtime(build.getAddtime());
            buildAndClassDto.setClassroom(classroomBeans);
            buildAndClassDtos.add(buildAndClassDto);
        }
        return buildAndClassDtos;
   }

    /**
     * 设备报修
     */
    @PostMapping("/deviceRepair")
    public int deviceRepair(@RequestParam("bulidid") String bulidid,
                            @RequestParam("classroomid") String classroomid,
                            @RequestParam("deviceid") String deviceid,
                            @RequestParam("desc") String desc,
                            HttpSession session) {
        if(bulidid == null || classroomid == null || deviceid == null || desc == null || "".equals(desc))
            return 0;
        User user = (User) session.getAttribute("loginPhoUser");
        if(user == null) return 0;
        //封装工单对象
        WorkOrder workOrder = new WorkOrder();
        workOrder.setApplicant(user.getUserrealname());
        workOrder.setSchoolid(user.getSchoolid());
        workOrder.setTbuildid(bulidid);
        workOrder.setClassroomid(classroomid);
        workOrder.setUsertel(user.getUsertel());
        workOrder.setRepairtime(new Date());
        workOrder.setReproblem(deviceid + "号设备：" + desc);
       return workOrderMapper.insertSelective(workOrder);
    }

//    ==============================================================
//    第一次给手机端的接口
    /**
     * 登陆方法
     * @return
     */
    @PostMapping("/login")
    public String login(@RequestParam("username") String username,
                                    @RequestParam("password") String password,
                                        HttpServletRequest request) {
        //1、判空校验
        if(username == null || "".equals(username) || password == null || "".equals(password)) {
            return "0";
        }
        //2、手机号码检验
        Pattern p = Pattern.compile("^[1][3,4,5,7,8][0-9]{9}$"); // 验证手机号
        Matcher m = p.matcher(username);
        if(!m.matches()) return "1";
        //3、进行登陆
        UserExample userExample = new UserExample();
        userExample.createCriteria()
                .andUsertelEqualTo(username)
                .andDelflagEqualTo(0);
        List<User> list = userMapper.selectByExample(userExample);
        if(list.size() == 0) return "2";
        User user = list.get(0);
        //验证密码
        if(!DigestUtils.md5DigestAsHex(("jgsu" + password + "c611").getBytes()).equals(user.getUserpwd())) return "3";

        //4、存入session
        HttpSession session = request.getSession();
        session.setAttribute("loginPhoUser",user);

        //5、写入登陆日志
        Date requestTime = new Date();
        Log log = new Log();
        log.setOperator(user.getUserrealname());
        log.setOpdescribe("手机端登陆");
        log.setOpermethod("login");
        log.setOpaddress(LogHandlerInterceptor.getIpAddr(request));
        log.setOpertime(requestTime);
        logMapper.insertSelective(log);

        //6、封装token
        String token = DigestUtils.md5DigestAsHex(user.getUsername().getBytes());
        return token;
    }

    @PostMapping("/getPhoneClassRoom")
    public List<phoneClassRoomDto> getPhoneClassRoom(HttpSession session) {
        //1、取出登陆用户的用户信息
        User user = (User) session.getAttribute("loginPhoUser");
        if(user == null) return null;
        String teacherName = user.getUserrealname();
        //根据名字去查课表
        ScheduleExample scheduleExample = new ScheduleExample();
        scheduleExample.createCriteria()
                .andTeachernameEqualTo(teacherName)
                .andDelflagEqualTo(0);
        List<Schedule> schedulelist = scheduleMapper.selectByExample(scheduleExample);

        List<phoneClassRoomDto> dtos = new ArrayList<>();
        for (Schedule schedule : schedulelist) {
            dtos.add(new phoneClassRoomDto(
                        schedule.getClassroomid(),
                        schedule.getSemesterid(),
                        schedule.getWeekseq(),
                        schedule.getWeek(),
                        schedule.getLesson(),
                        teacherName,
                        schedule.getCoursename(),
                        schedule.getClassname()
                    ));
        }
        return dtos;
    }

    /**
     * 获得登陆用户教室的全部网关
     */
    @PostMapping("/getAllGateWay")
    public List<GateWay> getAllGateWay(HttpSession session) {
        List<phoneClassRoomDto> rooms = getPhoneClassRoom(session);
        if(rooms == null) return null;
        List<GateWay> list = new ArrayList<>();
        for (phoneClassRoomDto room : rooms) {
            GateWayExample gateWayExample = new GateWayExample();
            gateWayExample.createCriteria()
                    .andClassroomidEqualTo(room.getClassname())
                    .andDelflagEqualTo(0);
            List<GateWay> gateWays = gateWayMapper.selectByExample(gateWayExample);
            list.addAll(gateWays);
        }
        return list;
    }

    /**
     * 网关详情
     */
    @PostMapping("/getGateWayMsg")
    public List<Device> getGateWayMsg(@RequestParam("gateWayId") String gateWayId) {
        if(gateWayId == null || "".equals(gateWayId)) return null;
        DeviceExample deviceExample = new DeviceExample();
        deviceExample.createCriteria()
                .andAfgatewayEqualTo(gateWayId)
                .andDelflagEqualTo(0);
        return deviceMapper.selectByExample(deviceExample);
    }

    /**
     * 删除网关
     */
    @PostMapping("/delWayMsg")
    public int delMsg(@RequestParam("gateWayId") String gateWayId) {
        if(gateWayId == null || "".equals(gateWayId)) return 0;
        //1、先查询是否有这个网关
        if(gateWayMapper.selectByPrimaryKey(gateWayId) == null) return 0;
        //删除网关
        GateWay gateWay = new GateWay();
        gateWay.setGatewayid(gateWayId);
        gateWay.setDelflag(1);
        return gateWayMapper.updateByPrimaryKeySelective(gateWay);
    }

    /**
     * 显示用户信息
     */
    @PostMapping("/getUserMsg")
    public UserMsgDto getUserMsg(HttpSession session) {
        User user = (User) session.getAttribute("loginPhoUser");
        if(user == null) return null;
        return new UserMsgDto(user.getUserid(),user.getUsertel(),user.getUsername(),user.getUseraddtime());
    }

    /**
     * 修改当前用户的手机号
     */
    @PostMapping("/updateTel")
    public int updateTel(@RequestParam("tel") String tel,HttpSession session) {
        if(tel == null || "".equals(tel)) return 0;
        //2、手机号码检验
        Pattern p = Pattern.compile("^[1][3,4,5,7,8][0-9]{9}$"); // 验证手机号
        Matcher m = p.matcher(tel);
        if(!m.matches()) return 0;
        User user = (User) session.getAttribute("loginPhoUser");
        if(user == null) return 0;
        User user1 = new User();
        user1.setUserid(user.getUserid());
        user1.setUsertel(tel);
        return userMapper.updateByPrimaryKeySelective(user1);
    }

    /**
     * 修改用户名
     * @param username
     * @param session
     * @return
     */
    @PostMapping("/updateusername")
    public int updateusername(@RequestParam("username") String username,HttpSession session) {
        if(username == null || "".equals(username)) return 0;
        User user = (User) session.getAttribute("loginPhoUser");
        if(user == null) return 0;
        User user1 = new User();
        user1.setUserid(user.getUserid());
        user1.setUsername(username);
        return userMapper.updateByPrimaryKeySelective(user1);
    }

    /**
     * 退出登陆
     */
    @PostMapping("/logout")
    public void logout(HttpSession session) {
        if(session.getAttribute("loginPhoUser") != null)
        session.removeAttribute("loginPhoUser");
    }
}

class BuildAndClassDto {

    /**
     * tbuildid : 00109
     * tbuildname : 第9教学楼
     * addtime : 2020-01-14 00:00:00
     * classroom : [{"classroomid":"00109A001","classroomname":"A001","addtime":"2020-01-01"}]
     */

    private String tbuildid;
    private String tbuildname;
    private Date addtime;
    private List<ClassroomBean> classroom;

    public String getTbuildid() {
        return tbuildid;
    }

    public void setTbuildid(String tbuildid) {
        this.tbuildid = tbuildid;
    }

    public String getTbuildname() {
        return tbuildname;
    }

    public void setTbuildname(String tbuildname) {
        this.tbuildname = tbuildname;
    }

    public Date getAddtime() {
        return addtime;
    }

    public void setAddtime(Date addtime) {
        this.addtime = addtime;
    }

    public List<ClassroomBean> getClassroom() {
        return classroom;
    }

    public void setClassroom(List<ClassroomBean> classroom) {
        this.classroom = classroom;
    }

    public static class ClassroomBean {
        /**
         * classroomid : 00109A001
         * classroomname : A001
         * addtime : 2020-01-01
         */

        private String classroomid;
        private String classroomname;
        private Date addtime;

        public String getClassroomid() {
            return classroomid;
        }

        public void setClassroomid(String classroomid) {
            this.classroomid = classroomid;
        }

        public String getClassroomname() {
            return classroomname;
        }

        public void setClassroomname(String classroomname) {
            this.classroomname = classroomname;
        }

        public Date getAddtime() {
            return addtime;
        }

        public void setAddtime(Date addtime) {
            this.addtime = addtime;
        }
    }
}

class AddGateWaysDto {

    /**
     * buildId : 00110
     * classroom : 000110A002
     * gateways : ["00:25:92:1b:8d:5e","00:25:92:1b:8d:5e","00:25:92:1b:8d:5e"]
     */

    private String buildId;
    private String classroom;
    private List<String> gateways;

    public String getBuildId() {
        return buildId;
    }

    public void setBuildId(String buildId) {
        this.buildId = buildId;
    }

    public String getClassroom() {
        return classroom;
    }

    public void setClassroom(String classroom) {
        this.classroom = classroom;
    }

    public List<String> getGateways() {
        return gateways;
    }

    public void setGateways(List<String> gateways) {
        this.gateways = gateways;
    }
}

class UserMsgDto {
    int userId;
    String userTel;
    String username;
    Date registerTime;

    public UserMsgDto(int userId, String userTel, String username, Date registerTime) {
        this.userId = userId;
        this.userTel = userTel;
        this.username = username;
        this.registerTime = registerTime;
    }

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    public String getUserTel() {
        return userTel;
    }

    public void setUserTel(String userTel) {
        this.userTel = userTel;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Date getRegisterTime() {
        return registerTime;
    }

    public void setRegisterTime(Date registerTime) {
        this.registerTime = registerTime;
    }

    @Override
    public String toString() {
        return "UserMsgDto{" +
                "userId=" + userId +
                ", userTel='" + userTel + '\'' +
                ", username='" + username + '\'' +
                ", registerTime=" + registerTime +
                '}';
    }
}

class phoneClassRoomDto {
    String classname;   //课室名称
    String teachSemester;   //上课学期
    String teachWeekSeq;   //上课周数
    int teachWeek;    //上课星期数
    int teachLesson; //第几节课
    String teacherName; //教师名字
    String lessonName;  //课程名字
    String classNmae;   //上课班级

    public phoneClassRoomDto(String classname, String teachSemester, String teachWeekSeq, int teachWeek, int teachLesson, String teacherName, String lessonName, String classNmae) {
        this.classname = classname;
        this.teachSemester = teachSemester;
        this.teachWeekSeq = teachWeekSeq;
        this.teachWeek = teachWeek;
        this.teachLesson = teachLesson;
        this.teacherName = teacherName;
        this.lessonName = lessonName;
        this.classNmae = classNmae;
    }

    public String getClassname() {
        return classname;
    }

    public void setClassname(String classname) {
        this.classname = classname;
    }

    public String getTeachSemester() {
        return teachSemester;
    }

    public void setTeachSemester(String teachSemester) {
        this.teachSemester = teachSemester;
    }

    public String getTeachWeekSeq() {
        return teachWeekSeq;
    }

    public void setTeachWeekSeq(String teachWeekSeq) {
        this.teachWeekSeq = teachWeekSeq;
    }

    public int getTeachWeek() {
        return teachWeek;
    }

    public void setTeachWeek(int teachWeek) {
        this.teachWeek = teachWeek;
    }

    public int getTeachLesson() {
        return teachLesson;
    }

    public void setTeachLesson(int teachLesson) {
        this.teachLesson = teachLesson;
    }

    public String getTeacherName() {
        return teacherName;
    }

    public void setTeacherName(String teacherName) {
        this.teacherName = teacherName;
    }

    public String getLessonName() {
        return lessonName;
    }

    public void setLessonName(String lessonName) {
        this.lessonName = lessonName;
    }

    public String getClassNmae() {
        return classNmae;
    }

    public void setClassNmae(String classNmae) {
        this.classNmae = classNmae;
    }

    @Override
    public String toString() {
        return "phoneClassRoomDto{" +
                "classname='" + classname + '\'' +
                ", teachSemester='" + teachSemester + '\'' +
                ", teachWeekSeq='" + teachWeekSeq + '\'' +
                ", teachWeek=" + teachWeek +
                ", teachLesson=" + teachLesson +
                ", teacherName='" + teacherName + '\'' +
                ", lessonName='" + lessonName + '\'' +
                ", classNmae='" + classNmae + '\'' +
                '}';
    }
}
